package cn.zyq.ykb.service.product.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.zyq.ykb.beans.pay.PayOrder;
import cn.zyq.ykb.beans.product.Product;
import cn.zyq.ykb.beans.product.ProductLink;
import cn.zyq.ykb.beans.user.User;
import cn.zyq.ykb.beans.user.UserBalance;
import cn.zyq.ykb.mapper.pay.PayOrderMapper;
import cn.zyq.ykb.mapper.product.ProductLinkMapper;
import cn.zyq.ykb.mapper.product.ProductMapper;
import cn.zyq.ykb.mapper.user.UserBalanceMapper;
import cn.zyq.ykb.mapper.user.UserMapper;
import cn.zyq.ykb.service.pay.PayOrderService;
import cn.zyq.ykb.service.product.ProductService;
import cn.zyq.ykb.system.common.BaseService;
import cn.zyq.ykb.system.enums.core.*;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.pay.core.enums.PayChannelEnum;
import cn.zyq.ykb.system.pay.core.enums.PayOrderStatusEnum;
import cn.zyq.ykb.system.task.delayQueue.DelayQueueManager;
import cn.zyq.ykb.system.task.delayQueue.DelayTask;
import cn.zyq.ykb.system.task.delayQueue.TaskBase;
import cn.zyq.ykb.system.utils.DateUtils;
import cn.zyq.ykb.system.utils.IPUtil;
import com.github.pagehelper.PageHelper;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import cn.zyq.ykb.mapper.product.ProductOrderMapper;
import cn.zyq.ykb.beans.product.ProductOrder;
import cn.zyq.ykb.service.product.ProductOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.zyq.ykb.system.common.PageParam;
import com.github.pagehelper.PageInfo;


import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 商品订单Service业务层处理
 *
 * @author SystemAuth
 * @date 2023-11-02
 */
@Service
@Slf4j
public class ProductOrderServiceImpl  extends BaseService implements ProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductLinkMapper productLinkMapper;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private UserBalanceMapper userBalanceMapper;
    @Autowired
    private DelayQueueManager delayQueueManager;
    @Autowired
    private PayOrderMapper payOrderMapper;
    /**
     * 查询商品订单
     *
     * @param productOrderID 商品订单主键
     * @return 商品订单
     */
    @Override
    public ProductOrder selectProductOrderByProductOrderID(Integer productOrderID) {
        ProductOrder productOrder = productOrderMapper.selectByPrimaryKey(productOrderID);
        if (productOrder.getDeleted() == 1) {
            return null;
        }
        Product product = this.productMapper.selectByPrimaryKey(productOrder.getProductID());
        productOrder.setProduct(product);
        User user = this.userMapper.selectByPrimaryKey(productOrder.getUserID());
        productOrder.setUser(user);
        this.productService.checkProductPriceByUser(product,user);
        if (productOrder.getOrderState().equals(TaskOrderStateEnum.ZFCG.getValue())){
            ProductLink link = new ProductLink();
            link.setProductID(product.getProductID());
            link.setDeleted(0);
            List<ProductLink> productLink = this.productLinkMapper.select(link);
            product.setProductLink(productLink);
        }
        return productOrder;
    }

    /**
     * 查询商品订单
     *
     * @param serviceID 业务ID
     * @return 商品订单
     */
    @Override
    public ProductOrder selectProductOrderByServiceID(String serviceID) {
        ProductOrder param = new ProductOrder();
        param.setDeleted(0);
        param.setServiceID(serviceID);
        return this.productOrderMapper.selectOne(param);
    }

    /**
     * 查询商品订单列表
     *
     * @param pageParam
     * @param param
     * @return 商品订单
     */
    @Override
    public PageInfo<ProductOrder> selectProductOrderList(PageParam pageParam, User param) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        pageParam.getKv().put("userID", param.getUserID());
        List<ProductOrder> list = this.productOrderMapper.list(pageParam.getKv());
        for (ProductOrder productOrder : list) {
            Product product = this.productMapper.selectByPrimaryKey(productOrder.getProductID());
            productOrder.setProduct(product);
            User user = this.userMapper.selectByPrimaryKey(productOrder.getUserID());
            productOrder.setUser(user);
            this.productService.checkProductPriceByUser(product,user);
        }
        return new PageInfo<>(list);
    }

    /**
     * 查询商品订单列表
     *
     * @param pageParam
     * @return 商品订单
     */
    @Override
    public PageInfo<ProductOrder> selectProductOrderListGL(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        List<ProductOrder> list = this.productOrderMapper.list(pageParam.getKv());
        for (ProductOrder productOrder : list) {
            Product product = this.productMapper.selectByPrimaryKey(productOrder.getProductID());
            productOrder.setProduct(product);
            User user = this.userMapper.selectByPrimaryKey(productOrder.getUserID());
            productOrder.setUser(user);
            this.productService.checkProductPriceByUser(product,user);
        }
        return new PageInfo<>(list);
    }

    /**
     * 查询商品订单列表
     *
     * @param pageParam
     * @return 商品订单
     */
    @Override
    public List<ProductOrder> selectProductOrderAllList(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
        pageParam.getKv().put("deleted", 0);
        return this.productOrderMapper.list(pageParam.getKv());
    }
    /**
     * 新增商品订单
     *
     * @param param 商品订单
     * @return 结果
     */
    @Override
    public int insertProductOrder(ProductOrder param) {
        this.setCreateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.productOrderMapper.insertSelective(param);
    }

    /**
     * 修改商品订单
     *
     * @param param 商品订单
     * @return 结果
     */
    @Override
    public int updateProductOrder(ProductOrder param) {
        this.setUpdateBaseData(param, SecurityUtils.getLoginUser().getSysAdmin());
        return this.productOrderMapper.updateByPrimaryKeySelective(param);
    }

    /**
     * 批量删除商品订单
     *
     * @param productOrderIDs 需要删除的商品订单主键
     * @return 结果
     */
    @Override
    public int deleteProductOrderByProductOrderIDs(Integer[] productOrderIDs) {
        int i = 0;
        for (Integer productOrderID : productOrderIDs) {
            i += this.deleteProductOrderByProductOrderID(productOrderID);
        }
        return i;
    }

    /**
     * 删除商品订单信息
     *
     * @param productOrderID 商品订单主键
     * @return 结果
     */
    @Override
    public int deleteProductOrderByProductOrderID(Integer productOrderID) {
        ProductOrder productOrder = this.selectProductOrderByProductOrderID(productOrderID);
        if (productOrder == null) {
            return 0;
        } else {
            ProductOrder storeInfo = new ProductOrder();
            storeInfo.setProductOrderID(productOrderID);
            storeInfo.setDeleted(1);
            storeInfo.setUpdateBy(SecurityUtils.getSysAdminID());
            storeInfo.setUpdateTime(LocalDateTime.now());
            this.productOrderMapper.updateByPrimaryKeySelective(storeInfo);
            return 1;
        }
    }

    @Override
    public ProductOrder placeOrder(Product param, HttpServletRequest request, User loginUser) {
        log.info("【【【【【【【【【【【【【【【【【【【【【【【【【【【【【【【【商品下单参数, {}】】】】】】】】】】】】】】】】】】】】】】】】】】】】】】】】】】",param.toString());
        Product product = this.productMapper.selectByPrimaryKey(param.getProductID());
        if (BeanUtil.isEmpty(product)){
            throw new BusinessException("当前商品不存在");
        }
        User user = this.userMapper.selectByPrimaryKey(loginUser.getUserID());
        this.checkLogicExist(user, "没有获取到下单用户信息");
        ProductOrder order = new ProductOrder();
        order.setUserID(user.getUserID());
        order.setProductID(product.getProductID());
        order.setDeleted(0);
        ProductOrder productOrder1 = this.productOrderMapper.selectOne(order);
        String orderCode = null;
        ProductOrder productOrder = new ProductOrder();
        if (BeanUtil.isEmpty(productOrder1)){
            orderCode = OrderTypeEnum.GMSP.getMarker() + user.getPhone() + System.currentTimeMillis();
//            ProductOrder productOrder = new ProductOrder();
            productOrder.setOrderCode(orderCode);
            productOrder.setUserID(user.getUserID());
            productOrder.setProductNum(1);
            productOrder.setProductPrice(param.getYhPrice());
            productOrder.setOrderState(OrderTypeEnum.GM.getValue());
            productOrder.setPayType(PayTypeEnum.ZFB.getValue());
            productOrder.setPayTime(LocalDateTime.now());
            productOrder.setPayExpireTime(LocalDateTime.now().plusMinutes(5L));
            productOrder.setProductID(product.getProductID());
            productOrder.setPrice(param.getYhPrice());
            this.setCreateBaseData(productOrder,user);
            int i = this.productOrderMapper.insertSelective(productOrder);
            if (i == 0){
                throw new BusinessException("商品下单失败");
            }
        }else {
            productOrder = productOrder1;
            orderCode = productOrder.getOrderCode();
        }
        Integer channelId=0;
        if (param.getPhoneSystems().equals(1)){
            channelId = PayChannelEnum.ALIPAY_APP_ANDROID.getChannelId();
        }else if (param.getPhoneSystems().equals(2)){
            channelId = PayChannelEnum.ALIPAY_WAP.getChannelId();
        }else {
            throw new BusinessException(ResponseCodeEnum.ERROR,"请传递正确的支付渠道码");
        }
        PayOrder order1 = new PayOrder();
        order1.setUserID(loginUser.getUserID());
        order1.setOrderCode(orderCode);
        order1.setDeleted(0);
        PayOrder payOrder = this.payOrderMapper.selectOne(order1);
//        PayOrder payOrder = new PayOrder();
        if (BeanUtil.isNotEmpty(payOrder)){
            this.payOrderMapper.deleteByPrimaryKey(payOrder.getPayOrderID());
        }
        //下单
        payOrder = new PayOrder(
                channelId,
                orderCode,
                "购买课程下单",
                "购买课程",
                IPUtil.getIPAddress(request),
                loginUser.getUserID(),
                PayOrderTypeEnum.GM.getValue(),
                productOrder.getProductOrderID(),
                param.getYhPrice(),
                PayOrderBusinessTypeEnum.GMKC.getValue(),
                new BigDecimal(0),
                LocalDateTime.now().plusMinutes(5L)
        );
        PayOrder pay = this.payOrderService.pay(payOrder, loginUser);
        String payReqRespInfo = pay.getPayReqResp();
        productOrder.setPayReqRespInfo(payReqRespInfo);
        if (pay.getExpireTime() != null && pay.getSuccessTime() == null) {
            long l = DateUtils.durationToMillis(LocalDateTime.now(), pay.getExpireTime());
            //加入延时队列
            TaskBase base = new TaskBase(productOrder.getServiceID(), 2, productOrder.getServiceID());
            //获取相差时间
            DelayTask task1 = new DelayTask(base, l);
            this.delayQueueManager.put(task1);
            log.info("订单：{}加入延时队列,过期时间{}", productOrder.getServiceID(), pay.getExpireTime());
        }
        return productOrder;
    }

    @Override
    public void payNotifyOrder(PayOrder payOrder) {
        //查询原订单
        ProductOrder productOrder = this.productOrderMapper.selectByPrimaryKey(payOrder.getRelatedOrderID());
        if (BeanUtil.isEmpty(productOrder)){
            throw new BusinessException("获取原商品订单失败");
        }
        ProductOrder updateInstance = this.getUpdateInstance(ProductOrder.class);
        updateInstance.setProductOrderID(productOrder.getProductOrderID());
        if (productOrder.getOrderState().equals(TaskOrderStateEnum.ZFCG.getValue())){
            if (PayOrderStatusEnum.NOTIFY_SUCCESS.getValue().equals(payOrder.getStatus())) {
                updateInstance.setOrderState(TaskOrderStateEnum.ZFCG.getValue());
                updateInstance.setFinishTime(LocalDateTime.now());
                updateInstance.setTotalPrice((payOrder.getNotifyPayerAmount()).divide(new BigDecimal(100)));
                //获取用户信息
                User user = this.userMapper.selectByPrimaryKey(productOrder.getUserID());
                //获取商品的原价
                Product product = this.productMapper.selectByPrimaryKey(productOrder.getProductID());
                BigDecimal price = product.getPrice();
                if (user.getPosition().equals(UserPositionEnum.TDZ.getValue())){
                    //获取服务商商品价格
                    double div = 0.7;
                    BigDecimal mul = price.multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                    //如果是团队长将差价添加到服务商的余额中
                    BigDecimal fallPrice = price.subtract(mul);
                    //获取上级服务商
                    User fwsUser = this.userMapper.selectByPrimaryKey(user.getService());
                    fwsUser.setWallet(fwsUser.getWallet().add(fallPrice));
                    this.userMapper.updateByPrimaryKeySelective(fwsUser);
                    //新增上级服务商余额变动明细
                    UserBalance userBalance = new UserBalance(
                            fwsUser.getUserID(),
                            fwsUser.getWallet().add(fallPrice),
                            fwsUser.getWallet(),
                            fallPrice,
                            productOrder.getProductOrderID(),
                            UserBalanceStatusEnum.GMSP.getValue(),
                            user.getUserID(),
                            "好友购买课程收益"
                    );
                    this.setCreateBaseData(userBalance, user);
                    this.userBalanceMapper.insertSelective(userBalance);

                }else if (user.getPosition().equals(UserPositionEnum.PT.getValue())){
                    //判断是个人任务还是服务商用户
                    if (user.getPerson() == 0){
                        //获取服务商商品价格
                        double div = 0.7;
                        BigDecimal mul = price.multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                        //如果是团队长将差价添加到服务商的余额中
                        BigDecimal fallPrice = price.subtract(mul);
                        //获取上级服务商
                        User fwsUser = this.userMapper.selectByPrimaryKey(user.getService());
                        fwsUser.setWallet(fwsUser.getWallet().add(fallPrice));
                        this.userMapper.updateByPrimaryKeySelective(fwsUser);
                        //新增上级服务商余额变动明细
                        UserBalance userBalance = new UserBalance(
                                fwsUser.getUserID(),
                                fwsUser.getWallet().add(fallPrice),
                                fwsUser.getWallet(),
                                fallPrice,
                                productOrder.getProductOrderID(),
                                UserBalanceStatusEnum.GMSP.getValue(),
                                user.getUserID(),
                                "好友购买课程收益"
                        );
                        this.setCreateBaseData(userBalance, user);
                        this.userBalanceMapper.insertSelective(userBalance);
                    }else {
                        //获取个人商品价格
                        double div = 0.8;
                        BigDecimal mul = price.multiply(new BigDecimal(div)).setScale(1,BigDecimal.ROUND_HALF_UP);
                        //如果是团队长将差价添加到服务商的余额中
                        BigDecimal fallPrice = price.subtract(mul);
                        //获取上级服务商
                        User grUser = this.userMapper.selectByPrimaryKey(user.getPerson());
                        grUser.setWallet(grUser.getWallet().add(fallPrice));
                        this.userMapper.updateByPrimaryKeySelective(grUser);
                        //新增上级服务商余额变动明细
                        UserBalance userBalance = new UserBalance(
                                grUser.getUserID(),
                                grUser.getWallet().add(fallPrice),
                                grUser.getWallet(),
                                fallPrice,
                                productOrder.getProductOrderID(),
                                UserBalanceStatusEnum.GMSP.getValue(),
                                user.getUserID(),
                                "好友购买课程收益"
                        );
                        this.setCreateBaseData(userBalance, user);
                        this.userBalanceMapper.insertSelective(userBalance);
                    }
                }
            }else {
                updateInstance.setOrderState(TaskOrderStateEnum.ZFSB.getValue());
            }
        }
        this.productOrderMapper.updateByPrimaryKeySelective(updateInstance);
    }

    @Override
    public void reloadStateQueue() {
        log.info("初始化未支付任务订单进入延时队列");
        PageParam pageParam = new PageParam();
        pageParam.setPage(1);
        pageParam.setPageSize(1000);
        boolean flag = true;
        while (flag) {
            //获取未支付的数据
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            List<ProductOrder> list = this.productOrderMapper.queryNoPayOrder();
            for (ProductOrder order : list) {
                if (LocalDateTime.now().isBefore(order.getPayExpireTime())) {
                    //加入延时队列
                    TaskBase base = new TaskBase(order.getServiceID(), 1, order.getServiceID());
                    long l = DateUtils.durationToMillis(LocalDateTime.now(), order.getPayExpireTime());
                    //获取相差时间
                    DelayTask task = new DelayTask(base, l);
                    this.delayQueueManager.put(task);
                    log.info("订单：{}加入延时队列，延时毫秒{}，过期时间：{}", order.getServiceID(), l, order.getPayExpireTime());
                } else {
                    log.info("订单：{}已过期", order.getServiceID());
                    //已过期
                    ProductOrder updateOrder = new ProductOrder();
                    updateOrder.setOrderState(TaskOrderStateEnum.ZFSB.getValue());
                    updateOrder.setProductOrderID(order.getProductOrderID());
                    this.productOrderMapper.updateByPrimaryKeySelective(updateOrder);
                }
            }
            //当获取的列表小于分页大小，则没有更多数据，停止轮询
            if (list.size() < pageParam.getPageSize()) {
                flag = false;
            } else {
                pageParam.setPage(pageParam.getPage() + 1);
            }
        }
    }
}
